<?php

namespace app\api\service;

use app\api\model\Product;
use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\api\model\UserAddress;
use app\lib\exception\UserException;
use app\api\model\Order as OrderModel;
use app\api\model\OrderProduct;
use think\Db;

class Order
{
	// 订单的商品列表,也就是客户端传递过来的products参数
	protected $oProducts;

	// 真实的商品信息(包括库存量)
	protected $products;

	protected $uid;

	// 从抖店获取订单
    public function getOrderFromDou()
    {
        // 获取access_token
        $dou = new DouAccessToken();
        $result = $dou->get();

        // 参数
        $app_key = config('dou.app_id');
        $app_secret = config('dou.app_secret');
        $access_token = $result["data"]["access_token"];
        $param_json = '{"is_desc":"1","order_by":"create_time","page":"0","size":"100"}';
        $timestamp = date('Y-m-dH:i:s');
        $sign = $app_secret."app_key".$app_key.
            "methodorder.listparam_json".$param_json.
            "timestamp".$timestamp."v2".$app_secret;
        $sign = md5($sign);

        // 获取订单列表url
        $order_list_url = sprintf(config('dou.order_list'), $app_key, $access_token, $param_json, $timestamp, $sign);

        // 获取订单列表
        $order_result = curl_get($order_list_url);
        $order_result = json_decode($order_result, true);

        if ($order_result['message'] == 'success'){
            if ($order_result['data']['count']){
                $order_data = $order_result['data']['list'];

//                return $order_data;
                Db::startTrans();
                try {
                    foreach ($order_data as $k=>$v)
                    {
                        $origin = $v['child'][0];

                        // 判断订单的状态
                        $order_status = $origin['order_status'];
                        if ($order_status == 21 || $order_status == 22)
                        {
                            $order_status = 7;
                        }elseif ($order_status == 24 || $order_status == 38){
                            $order_status = 7;
                        }elseif ($order_status == 39){
                            $order_status = 7;
                        }elseif ($order_status > 5){
                            $order_status = 6;
                        }

                        // 数据库是否存在这条订单
                        $is_order = Db::name('order')->where('ordernum', $origin['order_id'])->field('id,money,dealer_id')->find();

                        if ($is_order) {
                            $update_data = [];
                            $update_data['status'] = $order_status;

                            if ($order_status == 5) {
                                $ratio = Db::name('commission')->where('dealer_id', $is_order['dealer_id'])->order('updatetime desc')->field('firstratio')->find();

                                if ($ratio) {
                                    $commission = bcmul($is_order['money'], $ratio['firstratio'], 2);
                                    $commission = bcdiv($commission, 100, 2);
                                    $update_data['commission'] = $commission;
                                    $update_data['commission_status'] = '1';
                                    $update_data['commission_available'] = $commission;
                                }
                            }

                            if ($order_status == 7) {
                                $update_data['commission_status'] = '0';
                                $update_data['commission_available'] = '0';
                            }
                            
                            Db::name('order')->where('ordernum', $origin['order_id'])->update($update_data);
                        } else {
                            // 下单用户判定 数据库是否存在对应用户
                            $phone = $origin['post_tel'];
                            $consumer = Db::name('consumer')->where('phone', $phone)->field('id,admin_id,consumer_id,dealer_id')->find();

                            if ($consumer) {
                                $add_data = [];
                                $add_data['ordernum'] = $origin['order_id'];
                                $add_data['goods'] = $origin['product_name'];
                                $add_data['goodsimage'] = $origin['product_pic'];
                                $add_data['ordertime'] = date('Y-m-d H:i:s', $origin['create_time']);
                                $add_data['status'] = $order_status;
                                $add_data['money'] = bcdiv($origin['total_amount'],100,2);
                                $add_data['shop_id'] = $v['shop_id'];      // 店铺id

                                // 查询有没有此店铺id的店铺
                                $is_shop = Db::name('shop')->where('shop_id',$v['shop_id'])->field('shop_id')->find();
                                if (!$is_shop){
                                    Db::name('shop')->insert(['shop_id'=>$v['shop_id'],'name'=>'店铺_'.$v['shop_id']]);
                                }

                                $add_data['admin_id'] = $consumer['admin_id'];
                                $add_data['dealer_id'] = $consumer['dealer_id'];
                                $add_data['head_id'] = $consumer['consumer_id'];
                                $add_data['consumer_id'] = $consumer['id'];
                                $add_data['createtime'] = $origin['create_time'];

                                if ($order_status == 5) {
                                    $ratio = Db::name('commission')->where('dealer_id', $consumer['dealer_id'])->field('firstratio')->find();

                                    if ($ratio) {
                                        $commission = bcmul($add_data['money'], $ratio['firstratio'], 2);
                                        $commission = bcdiv($commission, 100, 2);
                                        $add_data['commission'] = $commission;
                                        $add_data['commission_status'] = '1';
                                        $add_data['commission_available'] = $commission;
                                    }
                                }
                                $add_data['receiver'] = $origin['post_receiver'];
                                $add_data['phone'] = $phone;
                                $address = $origin['post_addr'];
                                $add_data['address'] = $address['province']['name'] . $address['city']['name'] . $address['town']['name'] . $address['detail'];

                                Db::name('order')->insert($add_data);

                                // 添加订单快照
                                $order_snap['order_content'] = json_encode($origin);
                                $order_snap['createtime'] = time();
                                Db::name('order_snap')->insert($order_snap);

                                Db::name('dou_log')->insert(['num'=>$order_result['data']['count'],'time'=>date('Y-m-d H:i:s')]);
                            }
                        }
                    }

                    Db::commit();

                    return true;

                }
                catch (Exception $ex)
                {
                    Db::rollback();
                    Log::error($ex);

                    return false;
                }
            }
        }else{
            return false;
        }

//        return $order_result;
    }

	public function place($uid, $oProducts)
	{
		// oProducts 和 products 作对比
		// 真实的商品信息,包括库存量
		// products从数据库中查询出来
		$this->oProducts = $oProducts;
		$this->products = $this->getProductsByOrder($oProducts);
		$this->uid = $uid;
		$status = $this->getOrderStatus();

		if(!$status['pass']){
			$status['order_id'] = -1;

			return $status;
		}

		// 开始创建订单
		$orderSnap = $this->snapOrder($status);
		$order = $this->createOrder($orderSnap);
		$order['pass'] = true;

		return $order;
	}

	// 生成订单
	private function createOrder($snap)
	{
		Db::startTrans();
		try
		{
			$orderNo = $this->makeOrderNo();
			$order = new OrderModel();
			$order->user_id = $this->uid;
			$order->order_no = $orderNo;
			$order->total_price = $snap['orderPrice'];
			$order->total_count = $snap['totalCount'];
			$order->snap_img = $snap['snapImg'];
			$order->snap_name = $snap['snapName'];
			$order->snap_address = $snap['snapAddress'];
			$order->snap_items = json_encode($snap['pStatus']);

			$order->save();

			$orderID = $order->id;
			$create_time = $order->create_time;

			foreach ($this->oProducts as &$p)
			{
				$p['order_id'] = $orderID;
			}
			$orderProduct = new OrderProduct();
			$orderProduct->saveAll($this->oProducts);
			Db::commit();

			return [
				'order_no' => $orderNo,
				'order_id' => $orderID,
				'create_time' => $create_time
			];
		}
		catch (\Exception $ex)
		{
			Db::rollback();
			throw $ex;
		}
	}

	// 生成订单编号
	public function makeOrderNo()
	{
		$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
		$orderSn = 
			$yCode[intval(date('Y')) - 2019] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

		return $orderSn;
	}

	// 生成订单快照
	private function snapOrder($status)
	{
		$snap = [
			'orderPrice' => 0,
			'totalCount' => 0,
			'pStatus' => [],
			'snapAddress' => null,
			'snapName' => '',
			'snapImg' => ''
		];

		$snap['orderPrice'] = $status['orderPrice'];
		$snap['totalCount'] = $status['totalCount'];
		$snap['pStatus'] = $status['pStatusArray'];
		$snap['snapAddress'] = json_encode($this->getUserAddress());
		$snap['snapName'] = $this->products[0]['name'];
		$snap['snapImg'] = $this->products[0]['main_img_url'];

		if(count($this->products) > 1){
			$snap['snapName'] .= '等';
		}

		return $snap;
	}

	// 获取用户地址
	private function getUserAddress()
	{
		$userAddress = UserAddress::where('user_id', '=', $this->uid)->find();

		if(!$userAddress){
			throw new UserException([
				'msg' => '用户收获地址不存在,下单失败',
				'errorCode' => 60001
			]);
		}

		return $userAddress->toArray();
	}

	// 外界调用查询库存量状态
	public function checkOrderStock($orderID)
	{
		$oProducts = OrderProduct::where('order_id','=',$orderID)->select();
		$this->oProducts = $oProducts;
		$this->products = $this->getProductsByOrder($oProducts);
		$status = $this->getOrderStatus();

		return $status;
	}

	// 获取订单状态
	private function getOrderStatus()
	{
		$status = [
			'pass' => true,
			'orderPrice' => 0,
			'totalCount' => 0,
			'pStatusArray' => []
		];

		foreach($this->oProducts as $oProduct)
		{
			$pStatus = $this->getProductStatus(
				$oProduct['product_id'],$oProduct['count'],$this->products
			);

			if(!$pStatus['haveStock']){
				$status['pass'] = false;
			}
			$status['orderPrice'] += $pStatus['totalPrice'];
			$status['totalCount'] += $pStatus['counts'];
			array_push($status['pStatusArray'], $pStatus);
		}

		return $status;
	}

	// 获取订单中每个商品的状态
	private function getProductStatus($oPID, $oCount, $products)
	{
		$pIndex = -1;

		$pStatus = [
			'id' => null,
			'haveStock' => false,
			'counts' => 0,
			'price' => 0,
			'name' => '',
			'totalPrice' => 0,
			'main_img_url' => null
		];

		for($i=0; $i<count($products); $i++){
			if($oPID == $products[$i]['id']){
				$pIndex = $i;
			}
		}

		if($pIndex == -1){
			// 客户端传递的product_id有可能根本不存在
			throw new OrderException([
				'msg' => 'id为'.$oPID.'的商品不存在,创建订单失败'
			]);
		}else{
			$product = $products[$pIndex];
			$pStatus['id'] = $product['id'];
			$pStatus['name'] = $product['name'];
			$pStatus['counts'] = $oCount;
			$pStatus['price'] = $product['price'];
			$pStatus['totalPrice'] = $product['price'] * $oCount;
			$pStatus['main_img_url'] = $product['main_img_url'];

			if($product['stock'] - $oCount >= 0){
				$pStatus['haveStock'] = true;
			}
		}

		return $pStatus;
	}

	// 根据订单信息查找真实的商品信息
	private function getProductsByOrder($oProducts)
	{
		// 不要使用foreach循环查询数据库
		$oPIDs = [];
		foreach($oProducts as $item){
			array_push($oPIDs, $item['product_id']);
		}
		$products = Product::all($oPIDs)
			->visible(['id', 'price', 'stock', 'name', 'main_img_url'])
			->toArray();

		return $products;
	}

	public function delivery($orderID, $jumpPage='')
	{
		$order = OrderModel::where('id', '=', $orderID)
			->find();

		if(!$order){
			throw new OrderException();
		}
		if($order->status != OrderStatusEnum::PAID){
			throw new OrderException([
				'msg' => '还没付款呢, 想干嘛? 或者你已经更新过订单了, 不要再刷了',
				'errorCode' => 80002,
				'code' => 403
			]);
		}
		$order->status = OrderStatusEnum::DELIVERED;
		$order->save();
//				->update(['status' => OrderStatusEnum::DELIVERED]);
		$message = new DeliveryMessage();

		return $message->sendDeliveryMessage($order, $jumpPage);
	}
}